import { Menu, Dropdown, Space, Badge, notification } from 'antd';
import React, { useMemo, useEffect } from 'react';
import { useModel, history } from 'umi';
import styles from './index.less';
import IconFont from '../base/IconFont';
import { DownOutlined } from '@ant-design/icons';
import { removeToken } from '@/services/user';
import _ from 'lodash';
export type SiderTheme = 'light' | 'dark';

const GlobalHeaderRight: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { flowDoing } = useModel('sysInfo', (ret) => ({
    flowDoing: ret.flowDoing,
  }));
  useEffect(() => {
    const handleBeforeUnload = () => {
      const unloadTime = new Date().getTime();
      localStorage.setItem('unloadTime', unloadTime.toString());
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);
  if (!initialState || !initialState.settings) {
    return null;
  }
  const user = initialState?.user;
  if (_.isEmpty(user)) {
    return null;
  }
  const sysInfo = initialState?.sys;
  if (_.isEmpty(sysInfo)) {
    return null;
  }
  const menuDatas = sysInfo?.menuDatas;
  if (_.isEmpty(menuDatas)) {
    return null;
  }
  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }
  const handleMenuClick = ({ key }: any) => {
    if (key === 'home') {
      history.push('/');
      return;
    } else if (key === 'password') {
      history.push('/xtgl/changepwd');
      return;
    } else if (key === 'logout') {
      removeToken();
      history.push('/user/login');
    } else if (key === '-6') {
      history.push('/yxgx/flowdoing');
    } else {
      const ids = key.split('_');
      if (!ids && ids.length !== 3) {
        return;
      }
      let permid = Number(ids[1]);
      const stepID = Number(ids[2]);
      if (stepID === 1) {
        permid = permid - 1;
      }
      const findMenu = (mDatas: API.MenuData[]): API.MenuData | undefined => {
        for (let index = 0; index < mDatas.length; index++) {
          if (mDatas[index].routes) {
            const mData = findMenu(mDatas[index].routes!);
            if (mData) {
              return mData;
            }
          } else {
            if (mDatas[index].id === permid) {
              return mDatas[index];
            }
          }
        }
        return undefined;
      };
      const mData = findMenu(menuDatas!);
      const path = mData?.path;
      history.push(path!);
    }
  };
  const menu = (
    <Menu selectedKeys={[]} onClick={handleMenuClick} mode="horizontal">
      <Menu.Item key="home">
        <IconFont type="icon-shouye" />
        <span>首页</span>
      </Menu.Item>
      <Menu.Item key="password">
        <IconFont type="icon-mimaxiugai" /> <span>修改密码</span>
      </Menu.Item>
      <Menu.Item key="logout">
        <IconFont type="icon-zhongzhi" />
        <span>退出系统</span>
      </Menu.Item>
    </Menu>
  );
  const dateMenus = (
    <Menu>
      <Menu.Item>数仓:{sysInfo?.edwDate}</Menu.Item>
      <Menu.Item>ODS:{sysInfo?.odsDate}</Menu.Item>
      <Menu.Item>FTP: {sysInfo?.ftpDate}</Menu.Item>
      <Menu.Item>CAP: {sysInfo?.capDate}</Menu.Item>
    </Menu>
  );
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const todoList = useMemo(() => {
    let doCount = 0;
    const mItems: JSX.Element[] = [];
    if (!_.isEmpty(flowDoing?.list)) {
      flowDoing?.list.forEach((d) => {
        doCount += d.NUM;
        mItems.push(
          <Menu.Item key={'' + d.WFID + '_' + d.PermID + '_' + d.STEPID}>
            {`${d.WFNM}`}
            <Badge count={d.NUM} />
          </Menu.Item>,
        );
      });
    }
    const doMenus = (
      <Menu onClick={handleMenuClick}>
        {mItems}
        {/* <Menu.Item key="-6">更多...</Menu.Item> */}
      </Menu>
    );
    if (doCount > 0) {
      notification.info({
        message: '您有待办事宜',
        description: doMenus,
      });
    }
    return doCount > 0 ? (
      <Dropdown overlay={doMenus!}>
        <div className="ant-dropdown-link" onClick={(e) => e.preventDefault()}>
          我的待办
          <Badge count={doCount} />
          <DownOutlined />
        </div>
      </Dropdown>
    ) : null;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [flowDoing?.list]);
  return (
    <Space
      direction="vertical"
      className={className}
      style={{ marginRight: '20px', color: 'white' }}
    >
      <Space size={'large'}>
        {todoList}
        <Dropdown overlay={menu}>
          <div className="ant-dropdown-link" onClick={(e) => e.preventDefault()}>
            {user?.name}
            <DownOutlined />
          </div>
        </Dropdown>
        <Dropdown overlay={dateMenus}>
          <div className="ant-dropdown-link" onClick={(e) => e.preventDefault()}>
            数据日期
            <DownOutlined />
          </div>
        </Dropdown>
      </Space>
    </Space>
  );
};
export default GlobalHeaderRight;
